#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <pthread.h>
#include <getopt.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/resource.h>
#include <sys/time.h>


#define ARRAY_SIZE(x)		(sizeof(x)/sizeof(x[0]))
#define MAX_EVENTS		1000		
static inline void msleep(unsigned long ms);
static inline void print_usage(char *progname);
int socket_server_init(char *listen_ip,int listen_port);
void set_socket_rlimit(void);

int main(int argc,char *argv[])

{
	int		listenfd=-1;
	int		clientfd;
	int		serv_port = 0;
	int		daemon_run = 0;
	char		*progname = NULL;
	struct sockaddr_in	client_addr;
	socklen_t		cliaddr_len;
	int		opt;
	//fd_set		rdset;
	int		rv;
	int		i;
	int		j;
	int		found;
	//int		maxfd = 0;
	char		buf[1024];
	//int		fds_array[1024];
	//struct timeval	;
	int		epollfd;//
	struct epoll_event	event;//添加某一个fd
	struct epoll_event	event_array[MAX_EVENTS];//同时处理多少个客户端
	int		events;//多少个客户端发生的事件

	struct option	long_options[] = 
	{
		{"daemon",no_argument,NULL,'b'},
		{"port",required_argument,NULL,'p'},
		{"help",no_argument,NULL,'h'},
		{NULL,0,NULL,0}
	};

	progname = basename(argv[0]);

	while((opt = getopt_long(argc,argv,"bp:h",long_options,NULL)) != -1)
	{
		switch (opt)
		{
			case 'b':
				daemon_run=1;
			break;


			case 'p':
				serv_port=atoi(optarg);
			break;

			case 'h':
				print_usage(progname);
			return EXIT_SUCCESS;

			default:

			break;
			
		}
	}


	if(!serv_port)
	{
		print_usage(progname);
		return -1;
	}


	set_socket_rlimit();//文件描述符数量设置最大

	if( (listenfd=socket_server_init(NULL,serv_port)) < 0 )
	{
		printf("ERROR: %s sever listen on port %d failure\n",argv[0],serv_port);
		return -2;
	}

	printf("%s server start to liseten on port %d\n",argv[0],serv_port);

	/*设置程序后台运行*/

	if(daemon_run)
	{
		daemon(0,0);

	}

	if( (epollfd=epoll_create(MAX_EVENTS)) < 0 )//创建
	{
		printf("epoll_create() failure:%s\n",strerror(errno));
		return -3;
	}

	event.events = EPOLLIN|EPOLLET;
	event.data.fd = listenfd;
	printf("listenfd:%d\n",listenfd);

	if( epoll_ctl(epollfd,EPOLL_CTL_ADD,listenfd,&event) < 0 )//加入
	{
		printf("epoll add listen socket failure: %s\n",strerror(errno));
		return -4;	
	}


	for( ; ; )
	{
		//阻塞
		events = epoll_wait(epollfd,event_array,MAX_EVENTS,-1);
		if(events < 0)
		{
			printf("epoll failure: %s\n",strerror(errno));
			break;
		}
		else if (events == 0)
		{
			printf("epoll get timeout\n");
			continue;
		}

		/*返回值表示有多少个发生事件*/
		for(i=0;i<events;i++)
		{
			if( (event_array[i].events&EPOLLERR) || (event_array[i].events&EPOLLHUP) )
			{
				printf("epoll_wait get error on fd[%d]:%s\n",event_array[i].data.fd,strerror(errno));
				epoll_ctl(epollfd,EPOLL_CTL_DEL,event_array[i].data.fd,&event);//出差移除该fd
				close(event_array[i].data.fd);
			}

			//客户端开始连接
			if( event_array[i].data.fd == listenfd )
			{
			
				if( (clientfd = accept(listenfd,(struct sockaddr *)NULL,NULL)) == -1 )
				{
				printf("Accept new client failure: %s\n",strerror(errno));
				continue;
				}
				
				event.data.fd = clientfd;
				event.events  = EPOLLIN|EPOLLET;
				if( epoll_ctl(epollfd,EPOLL_CTL_ADD,clientfd,&event) < 0 )//加入
				{
					printf("epoll add client socket failure: %s\n",strerror(errno));
					close(event_array[i].data.fd);
					continue;
				}
				printf("epoll add new client socket[%d]ok.\n",clientfd);
			}

		
		
			else/*连接上客户端，数据到达开始读数据*/
			{
				if( (rv = read(event_array[i].data.fd,buf,sizeof(buf))) <= 0 )
				{
					printf("socket[%d] read failure or get disconnect\n",event_array[i].data.fd);
					epoll_ctl(epollfd,EPOLL_CTL_DEL,event_array[i].data.fd,&event);
					close(event_array[i].data.fd);
					continue;
				}
				else
				{
					printf("socket[%d] read get %d bytes data\n",event_array[i].data.fd,rv);
					
					/*回复，小写大写转换*/
					for(j=0;j<rv;j++)
					{
						buf[j]=toupper(buf[j]);
					}

					if( write(event_array[i].data.fd,buf,rv) < 0 )
					{
						printf("socket[%d] write failure: %s\n",event_array[i].data.fd,strerror(errno));
						epoll_ctl(epollfd,EPOLL_CTL_DEL,event_array[i].data.fd,&event);
						close(event_array[i].data.fd);
					}

				}

			}
		
		}//for(i=0;;)
	}//死循环

CleanUp:
close(listenfd);
return 0;
}



/*static inline void msleep(unsigned long ms)
{
	struct timeval;
	tv.tv.sec = ms/1000;
	tv.tv.usec = (ms%1000)*1000;

	select(0,NULL,NULL,NULL,&tv);
}
*/
static inline void print_usage(char *progname)
{
	printf("Usage: %s [OPTION]...\n",progname);
	printf(" %s is a socket server program,which used to verify client and echo back string from it\n",progname);
	printf("\nMandatory arguments to long options are mandatory for short options too:\n");
	printf(" -b[daemon] Set program running on background\n");
	printf(" -p[PORT] Socket server listen port addr\n");
	printf(" -h[HELP] Display this help information\n");
	printf("\nExample: %s -b -p 8900\n",progname);
	return;
}

int socket_server_init(char *listen_ip,int listen_port)
{
	struct sockaddr_in	server_addr;
	int			rv = 0;
	int			on = 1;
	int			listenfd=-1;


	listenfd = socket(AF_INET,SOCK_STREAM,0);
	if( listenfd < 0)
	{
		printf("Creat server socket failure: %s\n",strerror(errno));
		return -1;
	}

	setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
	
	memset(&server_addr,0,sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(listen_port);

	if(!listen_ip)
	{
		server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	}
	else
	{
		if(inet_pton(AF_INET,listen_ip,&server_addr.sin_addr) <= 0)
		{
			printf("inet_pton() set listen IP address failure.\n");
			rv = -2;
			goto CleanUp;
		}
	}

	if( (rv=bind(listenfd,(struct sockaddr *)&server_addr,sizeof(server_addr))) < 0)
	{
		printf("bind the socket server failure: %s\n",strerror(errno));
		rv = -3;
		goto CleanUp;
	}

	if((rv=listen(listenfd,13)) < 0)
	{
		printf("listen() socket failure: %s\n",strerror(errno));
		rv = -4;
		goto CleanUp;
	}


	return listenfd;
CleanUp:
	close(listenfd);
	return 0;
}


void set_socket_rlimit(void)
{
	struct rlimit limit = {0};


	getrlimit(RLIMIT_NOFILE,&limit);
	limit.rlim_cur = limit.rlim_max;
	setrlimit(RLIMIT_NOFILE,&limit);

	printf("set socket open fd max count to %d\n",limit.rlim_max);
}
